using System;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using EqRepair.Code.Data;
using EqRepair.Code.Enums;

namespace EqRepair.Code.Classes
{
	public class Authentification
	{
		protected virtual string GetUserName()
		{
			return HttpContext.Current.User.Identity.Name;
		}
		protected virtual void SetUserName(string login)
		{
			FormsAuthentication.SetAuthCookie(login, false);
		}
		public EmployeeRole? GetCurrentUserRole()
		{
			int User;
			if (Int32.TryParse(GetUserName(), out User))
			{
				using (var db = new DataClasses2DataContext())
				{
					var d=db.Employees.FirstOrDefault(x => x.Id == User);
					if(d!=null)
					return (EmployeeRole)d.Role;
				}
			}
			return EmployeeRole.No;
		}

		public bool IsUserLogIn()
		{
			int User;
			if (Int32.TryParse(GetUserName(), out User))
			{
				using (var db = new DataClasses2DataContext())
				{
					var d = db.Employees.FirstOrDefault(x => x.Id == User);
					if (d != null)
					{

						return true;
					}
				}
			}
			return false;
		}

		public  string GetCurrentUserFullName()
		{
			int User;
			if (Int32.TryParse(GetUserName(), out User))
			{
				using (var db = new DataClasses2DataContext())
				{
					return db.Employees.FirstOrDefault(x => x.Id == User).FullName;
				}
			}
			return "Anonymous";
		}
		public int GetCurrentUserID()
		{
			int User;
			if (Int32.TryParse(GetUserName(), out User))
			{
				return User;
			}
			return -1;
		}

		public  bool LogIn(string Login, string Passw)
		{
			using (var db = new DataClasses2DataContext())
			{

				Employee d = db.Employees.FirstOrDefault(
					x => x.Login ==
					     Login
					     &&
					     x.PasswordSHA1 == Helper.GetHash(Passw));
				if (d != null)
				{
					SetUserName(d.Id.ToString());
					return true;
				}
			}
			return false;
		}
		public virtual void LogOut()
		{
			FormsAuthentication.SignOut();
		}
	}

	public class SessionAuthentification:Authentification
	{
		private const string CURRENT_USER_ID_KEY = "current_user_id";

		protected HttpSessionState ht;
		protected override string GetUserName()
		{
			return ht[CURRENT_USER_ID_KEY] != null ? ht[CURRENT_USER_ID_KEY].ToString() : "";
		}

		protected override void SetUserName(string l)
		{
			 ht[CURRENT_USER_ID_KEY]=l;
		}
		
		public SessionAuthentification(HttpSessionState hti)
		{
			ht = hti;
		}

		public override void LogOut()
		{
			ht[CURRENT_USER_ID_KEY] = -1;
		}
	}
}